<template>
  <div>
    <common-head title="全部联系人"/>
    <div class="wrap">
      <van-address-list
        v-model="chosenAddressId"
        :list="list"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
        @select="choseContact"
      />
    </div>
  </div>
</template>

<script>
import CommonHead from '../../components/CommonHead.vue'
import { fetchContacts } from 'api'
export default {
  data () {
    return {
      chosenAddressId: -1,
      list: []
    }
  },
  created () {
    this.fetchContacts()
  },
  beforeRouteEnter (to, from, next) {
    localStorage.setItem('from', from.path)
    next()
  },
  methods: {
    choseContact (contact, index) {
      const from = localStorage.getItem('from')
      console.log(from, 'from')
      console.log(contact.id, 'contact')
      if (from === '/confirmorder') {
        this.$router.push({
          path: from,
          query: {
            id: contact.id
          }
        })
      }
    },
    onAdd () {
      this.$router.push('contactAdd')
    },
    onEdit (contact) {
      this.$router.push({
        path: '/contactUpdate',
        query: {
          id: contact.id
        }
      })
    },
    fetchContacts () {
      // 所有联系人
      fetchContacts({
        token: localStorage.getItem('token')
      }).then(res => {
        console.log(res)
        if (res.data.code === 0) {
          const contacts = res.data.data.result
          const contactArr = []
          contacts.forEach(contact => {
            // 循环每个联系人 所有key
            const obj = {}
            for (const key in contact) {
              switch (key) {
                case 'id':
                  obj.id = contact[key]
                  break
                case 'linkMan':
                  obj.name = contact[key]
                  break
                case 'mobile':
                  obj.tel = contact[key]
                  break
                case 'address':
                  obj.address = contact[key]
                  break
                case 'isDefault':
                  obj.isDefault = contact[key]
                  break
                default:
                  break
              }
            }
            contactArr.push(obj)
          })
          this.list = contactArr
          // 定义默认选中联系人id
          const contact = this.list.find(contact => contact.isDefault)
          // 如果有默认联系人 选中id 就是 默认联系人id 否则 给第一个
          if (contact) {
            this.chosenAddressId = contact.id
          } else {
            this.chosenAddressId = this.list[0].id
          }
        }
      })
    }
  },
  components: { CommonHead },
  name: 'contactList'
}
</script>

<style lang="scss" scoped>
.warp{
  padding-top: 44px;
}
</style>
